from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from backend.database import engine, Base
from backend.api import router
from backend.scheduler import backup_scheduler
from backend.config import settings
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 创建FastAPI应用
app = FastAPI(
    title="网络设备配置备份平台",
    description="自动备份网络设备配置，支持多种设备类型",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册API路由
app.include_router(router, prefix="/api", tags=["API"])

# 静态文件服务（前端）
try:
    app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="frontend")
except:
    logger.warning("前端文件未找到，请先构建前端项目")

@app.on_event("startup")
async def startup_event():
    """应用启动时执行"""
    logger.info("应用启动中...")
    # 启动自动备份任务，使用配置的间隔时间
    backup_scheduler.start_auto_backup_job(hours=settings.BACKUP_INTERVAL_HOURS)
    logger.info(f"自动备份调度器已启动，间隔: {settings.BACKUP_INTERVAL_HOURS} 小时")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时执行"""
    logger.info("应用关闭中...")
    backup_scheduler.stop()
    logger.info("自动备份调度器已停止")

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "ok", "message": "服务运行正常"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "backend.main:app",
        host=settings.APP_HOST,
        port=settings.APP_PORT,
        reload=True
    )
